import { ConfigService } from '@nestjs/config';
import { TypeOrmModule, TypeOrmModuleOptions } from '@nestjs/typeorm';

export class DatabaseModule {
  static forRootAsync() {
    return TypeOrmModule.forRootAsync({
      useFactory: DatabaseModule.factory,
      inject: [ConfigService],
    });
  }
  private static factory(configService: ConfigService): TypeOrmModuleOptions {
    return {
      type: 'mysql',
      logging: configService.get('database.logging', 'all'),
      host: configService.get('database.host', 'localhost'),
      port: configService.get<number>('database.port', 3306),
      username: configService.get('database.username', 'root'),
      password: configService.get('database.password', 'password'),
      database: configService.get('database.database', 'test'),
      synchronize: configService.get('database.synchronize', true),
      entities: [__dirname + '/**/*.entity{.ts,.js}'],
      charset: 'utf8mb4_unicode_ci',
    };
  }
}
